import { getCssVariableValue } from '@/utils/utils';
import moment from 'moment';
import { DATA_MAP } from '../helper';
import _ from 'lodash';

export const getKeys = (data = {}) => {
  return Object.keys(data)
    .filter((key) => key.includes('Value'))
    .map((i) => i.replace('Value', ''));
};

export const priceBaseOptions = {
  grid: { top: 12, left: 48, bottom: 75, right: 75 },
  legend: {
    textStyle: {
      color: getCssVariableValue('--chart-legend-color'),
    },
  },
  xAxis: [
    {
      scale: true,
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
      },
      axisLine: {
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisTick: {
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisPointer: {
        type: 'line',
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
    },
  ],
  yAxis: [
    {
      type: 'value',
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
      },
      axisTick: {
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      splitLine: {
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
  ],
  dataZoom: [
    {
      type: 'slider',
      bottom: 26,
      start: 0,
      end: 100,
      height: 20,
      show: true,
      backgroundColor: getCssVariableValue('--bg-form'),
      dataBackground: {
        dataBackground: {
          areaStyle: { opacity: 0 },
          lineStyle: { opacity: 0 },
        },
      },
      selectedDataBackground: {
        areaStyle: {
          color: getCssVariableValue('--font-primary'),
          opacity: 0.15,
        },
        lineStyle: { color: 'transparent' },
      },
      borderColor: 'transparent',
      handleStyle: {
        color: getCssVariableValue('--bg-form'),
        borderColor: getCssVariableValue('--bd'),
      },
      brushSelect: false,
      showDetail: false,
    },
  ],
  tooltip: {
    formatter: (params) => {
      return params
        .map((x) => {
          const typename = x.seriesIndex === 0 ? '实时' : '日前';
          return `<div style="display:flex;align-items:center;">
                    <div>
                      <div style="display:flex;align-items:center;">
                        <div style="width:8px;height:8px;border-radius:4px;background:${
                          x.color
                        };"></div>
                        <div style="color:#A7A8A9;margin:0 4px;">${typename}价格</div>
                      </div>
                      <div style="display:flex;align-items:center;">
                        <div style="width:8px;height:8px;border-radius:4px;background:${
                          x.color
                        };"></div>
                        <div style="color:#A7A8A9;margin:0 4px;">${typename}竞价空间</div>
                      </div>
                    </div>
                    <div style="color:#A7A8A9;text-align:right;">
                      <div>${_.isNull(x.value?.[1]) ? '-' : _.round(Number(x.value?.[1]), 2)}</div>
                      <div>${_.isNull(x.value?.[0]) ? '-' : _.round(Number(x.value?.[0]), 3)}</div>
                    </div>
                  </div>`;
        })
        .join('');
    },
  },
  title: '日期选择',
  label: {
    color: getCssVariableValue('--chart-font-color'),
  },
  lineStyle: { color: getCssVariableValue('--chart-x-line') },
  checkpointStyle: {
    symbolSize: 10,
    borderWidth: 2,
    color: 'white',
    borderColor: getCssVariableValue('--bd-primary'),
  },
};

export const getSeries = (value = {}, isRevised) => {
  const data = _.cloneDeep(value);
  // 需要排除的名称(如果选择修正前则排除修正后，选择修正后则排除修正前)
  const excludeKeys = isRevised ? '修正前' : '修正后';
  let keys = getKeys(data);
  keys = keys.filter((k) => !data[k + 'Source'].includes(excludeKeys));
  return keys.map((k) => {
    const arr = data?.[k + 'Value']?.map((i) => (_.isNull(i) ? '-' : i)) || [];
    const name = data?.[k + 'Source']?.replace(isRevised ? '修正后' : '修正前', '');
    const color = data?.[k + 'Color'];
    return {
      data: arr,
      type: name?.includes('实时') || name?.includes('备用') ? 'line' : 'dashed',
      name,
      color,
    };
  });
};

export const baseOptions = {
  dataset: { dimensions: [], source: [] },
  grid: { top: 12, left: 48, bottom: 75, right: 75 },
  legend: {
    textStyle: {
      color: getCssVariableValue('--chart-legend-color'),
    },
  },
  tooltip: {},
  dataZoom: [
    {
      type: 'slider',
      bottom: 26,
      start: 0,
      end: 100,
      height: 20,
      show: true,
      backgroundColor: getCssVariableValue('--bg-form'),
      dataBackground: {
        dataBackground: {
          areaStyle: { opacity: 0 },
          lineStyle: { opacity: 0 },
        },
      },
      selectedDataBackground: {
        areaStyle: {
          color: getCssVariableValue('--font-primary'),
          opacity: 0.15,
        },
        lineStyle: { color: 'transparent' },
      },
      borderColor: 'transparent',
      handleStyle: {
        color: getCssVariableValue('--bg-form'),
        borderColor: getCssVariableValue('--bd'),
      },
      brushSelect: false,
      showDetail: false,
    },
  ],
  yAxis: [
    {
      type: 'value',
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
      },
      axisTick: {
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
  ],
};

export const getAllDates = (starDate, endDate) => {
  const dates = [];
  const currentDate = starDate.clone();

  // 循环添加日期直到超过结束日期
  while (currentDate.isSameOrBefore(endDate)) {
    dates.push(currentDate.format('MMDD'));
    currentDate.add(1, 'day'); // 增加一天
  }

  return dates;
};

export const getXAxis = (arr = [], dates = [], type = 96) => {
  const xAxis = [];
  const length = Math.floor(dates.length * type);
  Array.from({ length }).forEach((_, index) => {
    const indexDate = dates[Math.floor(index / type)];
    xAxis.push(indexDate + ' ' + arr[index]);
  });
  return {
    type: 'category',
    formatter: (v) => v.slice(4),
    axisLabel: {
      color: getCssVariableValue('--chart-font-color'),
    },
    axisLine: {
      lineStyle: {
        type: 'solid',
        color: getCssVariableValue('--chart-x-line'),
      },
    },
    data: xAxis || [],
  };
};

export const getTableData = (data = {}, tableKeys = [], isRevised) => {
  const arr = [];
  tableKeys.forEach((k) => {
    const name = DATA_MAP?.[k]?.name;
    const unit = DATA_MAP?.[k]?.unit;
    const obj = {
      t: name + ' ' + `(${unit})`,
      id: _.uniqueId('f'),
      children: [],
    };
    const series = getSeries(data[k], isRevised);
    series.map((v) => {
      const childObj = {
        t: v.name,
        id: _.uniqueId('c'),
      };
      v.data.map((d, i) => {
        childObj[i + 1 + ''] = d;
      });
      obj.children.push(childObj);
    });
    arr.push(obj);
  });
  return arr;
};

// 获取散点图的
const getScatterSeries = (startLen, endLen, data = []) => {
  const series = { data: [] };
  data = data.map((d) => {
    if (startLen === d.data.length) {
      return d;
    } else {
      d.data = d.data.slice(startLen, endLen);
      return d;
    }
  });
  data.forEach((i) => {
    const length = i?.data?.length;
    Array.from({ length }).forEach((_, t) => {
      series.data[t] = series.data[t] ? series.data[t] : [];
      series.data[t].push(i?.data?.[t]);
    });
  });
  return series;
};

export const getPriceChart = (data, dates, isRevised, type = 96) => {
  let series = getSeries(data, isRevised);
  series = series.map((i) => {
    i.data = i.data.map((d) => (d === '-' || d === null ? 0 : d));
    return i;
  });
  const date = [...dates, '全部'];
  const day = series.filter((i) => i.name.includes('日前'));
  const now = series.filter((i) => i.name.includes('实时'));
  const obj = {};
  date.forEach((d, i) => {
    let newDay = _.cloneDeep(day);
    let newNow = _.cloneDeep(now);
    const startLen = Math.floor(i * type);
    const endLen = Math.floor((i + 1) * type);
    const daySeries = getScatterSeries(startLen, endLen, newDay);
    const nowSeries = getScatterSeries(startLen, endLen, newNow);
    obj[d] = [nowSeries, daySeries];
  });

  const options = [];
  Object.keys(obj)
    .reverse()
    .forEach((k) => {
      options.push({ series: obj[k] });
    });
  return {
    ...priceBaseOptions,
    timeline: {
      data: date.reverse(),
      title: '日期选择',
      options: options,
      label: {
        color: getCssVariableValue('--chart-font-color'),
      },
      lineStyle: { color: getCssVariableValue('--chart-x-line') },
      checkpointStyle: {
        symbolSize: 10,
        borderWidth: 2,
        color: 'white',
        borderColor: getCssVariableValue('--bd-primary'),
      },
    },
    series: [
      {
        type: 'scatter',
        name: '实时价格与竞价空间相关性',
        props: {
          symbolSize: 8,
          legendHoverLink: false,
          itemStyle: { color: '#E86452', borderWidth: 1, borderColor: 'rgba(34, 38, 41, 0.5)' },
          emphasis: { itemStyle: { borderWidth: 1, borderColor: 'rgba(255, 255, 255, 0.85)' } },
        },
      },
      {
        type: 'scatter',
        name: '日前价格与竞价空间相关性',
        props: {
          symbolSize: 8,
          legendHoverLink: false,
          itemStyle: { color: '#5E92F6', borderWidth: 1, borderColor: 'rgba(34, 38, 41, 0.5)' },
          emphasis: { itemStyle: { borderWidth: 1, borderColor: 'rgba(255, 255, 255, 0.85)' } },
        },
      },
    ],
  };
};

export const getOptions = (value = {}, formValue, isRevised) => {
  const type = Number(formValue.type);
  const data = _.cloneDeep(value);
  const dates = getAllDates(moment(formValue.startDate), moment(formValue.endDate));
  const keys = Object.keys(data);
  const options = {};
  keys.forEach((key) => {
    // 获取竞价空间散点图
    if (key === 'biddingSpaceCorrelationMap') {
      options[key] = getPriceChart(data[key], dates, isRevised, Number(type));
    } else {
      const series = getSeries(data[key], isRevised);
      const xAxis = getXAxis(data[key]?.xAxis, dates, Number(type));
      options[key] = {
        ...baseOptions,
        xAxis: [xAxis],
        series,
      };
    }
  });
  return options;
};
